﻿#region Copyright
// 
// Copyright (C) 2010 VirtualStaticVoid <virtualstaticvoid@gmail.com>
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
#endregion

namespace IoCWrap
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Reflection;

  internal static class TypeFinder
  {

    public static IEnumerable<Type> FindConcreteTypesOf<TBaseType>()
      where TBaseType : class
    {
      return FindConcreteTypesOf<TBaseType>(true);
    }

    public static IEnumerable<Type> FindConcreteTypesOf<TBaseType>(bool publicTypesOnly)
      where TBaseType : class
    {
      return FindConcreteTypesOf<TBaseType>(publicTypesOnly, typeof (TBaseType).Assembly);
    }

    public static IEnumerable<Type> FindConcreteTypesOf<TBaseType>(bool publicTypesOnly, params Assembly[] assemblies)
      where TBaseType : class
    {
      IList<Type> foundTypes = new List<Type>();
      for (int i = 0; i < assemblies.Length; i++)
      {
        FindConcreteTypesOf<TBaseType>(publicTypesOnly, assemblies[0])
          .ForEach(foundTypes.Add);
      }
      return foundTypes;
    }

    public static IEnumerable<Type> FindConcreteTypesOf<TBaseType>(bool publicTypesOnly, Assembly assembly)
      where TBaseType : class
    {
      Type baseType = typeof(TBaseType);

      var foundTypes =
        from type in assembly.GetTypes()
        where (publicTypesOnly && type.IsPublic) && type.IsClass && !type.IsAbstract && baseType.IsAssignableFrom(type)
        select type;

      return foundTypes;
    }

  }
}
